<?php
/**
 * Copyright (c) 2018-2019.
 *  This file is part of the moonpie production
 *  (c) johnzhang <875010341@qq.com>
 *  This source file is subject to the MIT license that is bundled
 *  with this source code in the file LICENSE.
 */

namespace moonpie\plugin\wechat_account\validate;


use think\Validate;

class CachingTypeValidator extends Validate
{
    protected  $rule = [
        'cacheType' => 'require|validCacheTypes',
        'cacheData' => 'validCacheData',
        'port' => 'integer|between:0,65535',
        'db_select' => 'integer|between:0,255',
    ];
    protected $field = [
        'cacheType' => '缓存类型',
        'cacheData' => '缓存配置',
        'host' => '主机地址',
        'password' => '主机授权密钥',
        'port' => '主机端口',
        'db_select' => '数据库ID',
    ];
    protected $scene = [
        'redis' => [
            'host', 'password', 'port', 'db_select',
        ],
        'init' => [
            'cacheType', 'cacheData',
        ],
    ];
    protected $currentScene = 'init';
    protected function validCacheTypes($type, $rule, $data, $field, $title)
    {
        $label = "{$field}.validCacheTypes";
        if(!in_array($type, $this->getValidCacheTypes())){
            $this->message($label, "{$title}的数据'{$type}'不是支持的缓存类型");
            return false;
        }
        return true;
    }
    protected function getValidCacheTypes()
    {
        return ['default', 'redis'];
    }
    protected function validCacheData($cache, $rule, $data, $field, $title)
    {
        $label = "{$field}.validCacheData";
        switch ($data['cacheType']) {
            case 'default':
                return true;
            case 'redis':
                $validator = new static();
                $result = $validator->scene('redis')->check($cache);
                if(!$result) {
                    $this->message($label, "{$title}存在错误配置信息：{$validator->getError()}");
                    return false;
                }
                return true;
            default:
                $this->message($label, "{$title}验证失败");
                return false;

        }
    }
}